/*
  usage:
    babel-node create.js --f filename
    babel-node create.js --d dirname
    babel-node create.js --id mongodb所在的id
*/
import mongoose from 'mongoose';
import fs from 'fs';
import {Dataset} from '../models';
import {prod_ip} from '../constant';
import {argv} from 'yargs';

const ip = argv.ip || prod_ip
const dir = argv.d
const filename = argv.f

mongoose.connect(`mongodb://${ip}/wise`);

const readfile = (filename) =>  new Promise( (resolve, reject) => {
  fs.readFile( filename,'utf8',(err, content) => {resolve(content)} )
})

const readdir = (path) => new Promise( (resolve, reject) => {
  fs.readdir( path, (err, files) => {resolve(files)} )
})

const saveDataset = async (dataset) => {
  const [metas, content] = dataset.split('--------\n');
  const [title,url,description,scene,month,freq,sendnum,recnum] = metas.split("\n");
  const newDS = new Dataset({title,url,description,scene,month,freq,sendnum,recnum,content})
  return await newDS.save()
}

const Allstuff = async () => {
  if(dir){
    const filenames = await readdir(dir)
    const contents = await Promise.all(filenames.map((f)=>'./data/'+f).map(readfile))
    const datasets = await Promise.all(contents.map(saveDataset))
  }
  if(filename){
    const content = await readfile(filename)
    const dataset = await saveDataset(content)
    console.log(`createDataset ${dataset._id}`)
  }
}

Allstuff().then(()=>{
  console.log("data async finished")
  mongoose.disconnect()
}).catch(console.log)
